package com.wash.shoes.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wash.shoes.domain.mtbusy.MtUpdateToken;
import com.wash.shoes.entity.MtAuthPo;
import com.wash.shoes.mapper.MtAuthMapper;
import com.wash.shoes.service.MtAuthService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 美团授权的回调 服务实现类
 * </p>
 *
 * @author ljg
 * @since 2024-09-12
 */
@Log4j2
@Service
public class MtAuthServiceImpl extends ServiceImpl<MtAuthMapper, MtAuthPo> implements MtAuthService {

    @Autowired
    MtUpdateToken mtUpdateToken;

    @Override
    public MtAuthPo getLastTokenByType(String type, String opBizCode, String developerId) {
        return this.baseMapper.getLastTokenByType(type, opBizCode, developerId);
    }

    @Override
    public String getLastTokenStr(String type, String opBizCode, String developerId) {
        MtAuthPo mtAuthPo = this.getLastTokenByType(type, opBizCode, developerId);
        long timeSecond = DateUtil.betweenMs(new Date(), mtAuthPo.getCreateTime()) / 1000;
        long leftHour = (Long.parseLong(mtAuthPo.getExpireIn()) - timeSecond) / 3600L;

        if (leftHour < 24 * 5) {
            // 重新获取token
            mtUpdateToken.updateToken(mtAuthPo.getId());
            log.info("5天之内授权到期，请注意重新授权还有 {} 小时到期", leftHour);
        } else if (leftHour < 0) {
            /*  */
            log.info("授权到期,请重新授权", leftHour);
            return null;
        }
        return mtAuthPo.getAccessToken();
    }
}
